
using System;
using System.Collections.Generic;

namespace AtDevice
{
    
    public class PhoneBookManager : IPhoneBookManager
    {
        private AtDevice _device;
        private static List<IPhoneBook> _phonebooks;
        
        public PhoneBookManager(AtDevice device)
        {
            _device = device;
        }

        private void QueryPhonebooks()
        {
            _phonebooks = new List<IPhoneBook>();

            // Example response: +CPBS: ("SM","DC","FD","LD","MC","ME","RC","EN","ON")
            AtResponse response = _device.ExecuteCommand(new AtCommand("CPBS").LongRequest());
            string responseData = response.Items[0].Data;
            
            foreach(var item in responseData.Trim(new char[]  {'(' , ')'}).Split(','))
            {
                _phonebooks.Add(new PhoneBook(_device, item.Trim('"')));
            }
        }
        
        public List<IPhoneBook> GetPhoneBooks()
        {
            if(_phonebooks == null)
            {
                QueryPhonebooks();
            }
            
            return _phonebooks;
        }

        public IPhoneBook GetDefaultPhonebook()
        {
            foreach(var phonebook in GetPhoneBooks())
                if(phonebook.GetName().Equals("SM"))
                    return phonebook;

            throw new ApplicationException("The SM phonebook isn't supported by the device");
        }
    }
}
